﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace WebApplication1.Core
{
    public class RouterHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var routeKey = request.RequestUri.Segments[2];
            if (!BootStartup.RoutingTable.ContainsKey(routeKey.TrimEnd('/')))
            {
                /*var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound);
                var content = new StringContent("Unknown route", Encoding.UTF8, "application/text");
                httpResponseMessage.Content = content;
                return httpResponseMessage;*/

                return await base.SendAsync(request, cancellationToken);
            }

            var routeUri = BootStartup.RoutingTable[routeKey.TrimEnd('/')];

            var query = request.RequestUri.PathAndQuery.Replace(routeKey, string.Empty).Replace("/ApiGateway", string.Empty);
            var forwardUriAsString = string.Format("{0}{1}", routeUri, query);
            request.RequestUri = new Uri(forwardUriAsString);
            var client = new HttpClient();
            if (request.Method == HttpMethod.Get)
                request.Content = null;
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
            return response;
        }
    }
}